package com.bignerdranch.android.criminalintent;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment {
	public static final String EXTRA_TIME = "com.bignerdranch.android.criminalintent.time";
	private Date mDate;

	public static TimePickerFragment newInstance(Date date) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_TIME, date);

		TimePickerFragment fragment = new TimePickerFragment();
		fragment.setArguments(args);

		return fragment;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mDate = (Date) getArguments().getSerializable(EXTRA_TIME);

		// Create calendar to get integers for month, day, etc.
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(mDate);

		int hour = calendar.get(Calendar.HOUR);
		int minute = calendar.get(Calendar.MINUTE);

		// Set view
		View v = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_time, null);
		final TimePicker picker = (TimePicker) v.findViewById(R.id.dialog_time_picker);
		picker.setCurrentHour(hour);
		picker.setCurrentMinute(minute);
		
		return new AlertDialog.Builder(getActivity())
				.setView(v)
				.setTitle(R.string.time_picker_title)
				.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Calendar calendar = Calendar.getInstance();
						calendar.setTime(mDate);
						
						int year = calendar.get(Calendar.YEAR);
						int month = calendar.get(Calendar.MONTH);
						int day = calendar.get(Calendar.DAY_OF_MONTH);
						int hour = picker.getCurrentHour();
						int minute = picker.getCurrentMinute();
						mDate = new GregorianCalendar(year, month, day, hour, minute).getTime();
						
						sendResult(Activity.RESULT_OK);
					}
				})
				.create();
	}

	private void sendResult(int resultCode){
		if(getTargetFragment() == null){
			return;
		}
		Intent i = new Intent();
		i.putExtra(EXTRA_TIME, mDate);
		getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, i);		
	}
}
